<?php
if (!defined('APP_ID')) { die('No direct script access allowed'); }

class User {
	/**
	 * Checks login information and return id of user if exists
	 */
	public static function checkLogin($login, $password) {
		$result = 0;

		$sql = Query::factory('select')
			->table("tbl_users")
			->fields('id')
			->where("(`login`='%s')", Database::escape($login))
			->where("(`password`='%s')", md5($password))
			->limit(1)
			->compile();

		$user = Database::query($sql)->row();
		if ($user) {
			$result = intval($user['id']);
		}

		return $result;
	}

	/**
	 * Return current user id
	 */
	public static function getId($user_id = 0) {
		if (empty($user_id)) {
			$user_id = Auth::getId();
		}
	
		return $user_id;
	}

	/**
	 * Return user name
	 */
	public static function getName($user_id = 0) {
		$result = 'Guest';
		$user_id = self::getId($user_id);
		
		if ($user_id > 0) {
			$sql = Query::factory('select')
				->table("tbl_users")
				->fields('name')
				->where("`id`='%d'", $user_id)
				->limit(1)
				->compile();

			$user = Database::query($sql)->row();
			if ($user) {
				$result = $user['name'];
			}
		}

		return $result;
	}
	
	public static function getDate($user_id, $time_stamp, $format = 'Y-m-d H:i:s') {
		if (!$time_stamp) {
			$time_stamp = time();
		}
		$user_info = self::getInfo($user_id, 'utc_offset,dst_offset');
		$result = date(
			$format,
			Tools::utcTime(
				$time_stamp,
				$user_info['utc_offset'],
				$user_info['dst_offset']
			)
		);
		return $result;
	}

	/**
	 * User in groups
	 */
	public static function inGroups($user_id = 0) {
		$result = array();
		$user_id = self::getId($user_id);
		
		// TODO: Select only opened and closed groups
		$sql = Query::factory('select')
			->table('tbl_user2group')
			->fields('group_id')
			->where('`user_id`=%d', $user_id)
			->compile();

		$groups = Database::query($sql)->rows();
		foreach ($groups as $group) {
			$result[] = intval($group['group_id']);
		}
		
		return $result;
	}

	/**
	 * Load access table
	 */
	public static function loadAccess($user_id) {
		$access = array(
			'list' => array(),
			'admin' => false
		);		
		
		if ((User::getId() == $user_id) && Config::get('access', null, false)) {
			$access = Config::get('access');
		} else {
			$in_groups = self::inGroups($user_id);
			if (in_array(Config::get('group_admin'), $in_groups)) {
				$access['admin'] = true;
			} else {
				$access['list']['system'] = 0;
				if (count($in_groups) > 0) {
					$rows = Query::factory('select')
						->table('tbl_access')
						->where('group_id IN (%s)', implode(',', $in_groups))
						->execute()
						->rows();
					foreach ($rows as $row) {
						if (is_null($row['controller']) && is_null($row['action'])) {
							$access['list']['system'] |= intval($row['value']);
						} else if (!is_null($row['controller']) && is_null($row['action'])) {
							$access['list'][$row['controller']] = 0;
							$access['list'][$row['controller']] |= intval($row['value']);
						} else {
							$access['list'][$row['controller'] . '_' . $row['action']] = 0;
							$access['list'][$row['controller'] . '_' . $row['action']] |= intval($row['value']);
						}
					}
				}
			}
			
			if (User::getId() == $user_id) {
				Config::set('access', $access);
			}
		}
		
		return $access;
	}

	/**
	 * Check access
	 */
	public static function checkAccess($user_id, $controller = null, $action = null) {
		$result = false;

		$access = User::loadAccess($user_id);

		if ((User::getId() == $user_id) && !Config::get('access', null, false)) {
			$access = User::loadAccess($user_id);
		} else if (User::getId() == $user_id) {
			$access = Config::get('access');
		} else {
			$access = User::loadAccess($user_id);
		}
		
		if ($access['admin']) {
			return true;
		} else {
			$path = '';
			if (is_null($controller) && is_null($action)) {
				$path = 'system';
			} else if (!is_null($controller) && is_null($action)) {
				$path = $controller;
			} else if (!is_null($controller) && !is_null($action)) {
				$path = $controller . '_' . $action;
			}
			
			if (!empty($path) && isset($access['list'][$path]) && Tools::bitCheck($access['list'][$path], 1)) {
				$result = true;
			}
		}
		
		return $result;
	}
	
	/**
	 * Get user info
	 */
	public static function getInfo($id, $fields = '*') {
		$id = self::getId($id);
		return Query::factory('select')
			->table('tbl_users')
			->fields($fields)
			->where('id=%d', $id)
			->limit(1)
			->execute()
			->row();
	}

	/**
	 * Is User in group
	 */
	public static function inGroup($user_id, $group_id) {
		$result = false;

		$row = Query::factory('select')
			->table('tbl_user2group')
			->fields('id')
			->where('user_id=%d', $user_id)
			->where('group_id=%d', $group_id)
			->limit(1)
			->execute()
			->row();
		if ($row) {
			$result = true;
		}

		return $result;
	}

	/**
	 * Add document to category
	 */
	public static function addToGroup($user_id, $group_id) {
		$result = false;
		
		if (($user_id > 0) && ($group_id > 0) && !self::inGroup($user_id, $group_id)) {
			$data = array();
			Query::data($data, 'user_id', $user_id, Query::DATA_INTEGER);
			Query::data($data, 'group_id', $group_id, Query::DATA_INTEGER);

			$id = Query::factory('insert')
				->table('tbl_user2group')
				->data($data)
				->execute()
				->getLastId();

			if ($id) {
				$result = true;
			}
		}
		
		return $result;
	}

	/**
	 * Remove document from category
	 */
	public static function removeFromGroup($user_id, $group_id) {
		$result = false;

		if (($user_id > 0) && ($group_id > 0) && self::inGroup($user_id, $group_id)) {
			$query = Query::factory('delete')
				->table('tbl_user2group')
				->where('user_id=%d', $user_id)
				->where('group_id=%d', $group_id)
				->execute();
			
			if (!$query->isError()) {
				$result = true;
			}
		}
		
		return $result;
	}

	/**
	 * Return list of users
	 */
	public static function getList($group_id = 0) {
		$query = Query::factory('select')
			->table('tbl_users', 'u')
			->fields('u.*')
			->where('u.status_id IN (1,2)')
			->orderBy('u.id', Query::ORDER_ASC);

		if ($group_id > 0) {
			$query->join('tbl_user2group', 'u2g')
				->on('u.id=u2g.user_id')
				->where('u2g.group_id=%d', $group_id);
		}
		
		return $query->execute()->rows();
	}

	/**
	 * Insert user
	 */
	public static function insert($data) {
		return Query::factory('insert')
			->table('tbl_users')
			->data($data)
			->execute()
			->getLastId();
	}

	/**
	 * Update user
	 */
	public static function update($id, $data) {
		$query = Query::factory('update')
			->table('tbl_users')
			->data($data)
			->where('id=%d', $id)
			->execute();

		return ($query->getAffectedRows() > -1);	
	}

	/**
	 * Delete document
	 */
	public static function delete($id, $data) {
		$query = Query::factory('update')
			->table('tbl_users')
			->data($data)
			->where('id=%d', $id)
			->execute();

		return ($query->getAffectedRows() > -1);	
	}
}
